package com.xjtu.controller;

import com.xjtu.config.ThreadPoolComponent;
import com.xjtu.service.NetworkService;
import com.xjtu.vo.AttackRecordVo;
import com.xjtu.vo.resp.Response;
import com.xjtu.vo.resp.ServerTrafficVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;

@RestController
@RequestMapping("/network")
@Api(tags = "网络拓扑模块")
public class NetworkController {
    @Autowired
    private NetworkService networkService;

    @Autowired
    private ThreadPoolComponent threadPoolComponent;

    private static final String TEMP_DIR = "src/main/resources/temp/";
    private static final String DEFAULT_TOPOLOGY_FILE = "src/main/resources/topology.json";

    public NetworkController() {
        // 确保 temp 文件夹存在
        File tempDir = new File(TEMP_DIR);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
    }

    /**
     * 用户上传文件并加载拓扑
     */
    @ApiOperation(value = "用户上传拓扑")
    @PostMapping("/load")
    public Response<String> loadTopology(@RequestPart("file") MultipartFile file) {
        try {
            String fileHash = calculateFileHash(file);
            File existingFile = new File(TEMP_DIR + fileHash + ".json");
            if (existingFile.exists()) {
                networkService.loadTopology(existingFile.getAbsolutePath());
                return Response.success("Topology loaded successfully from existing file!");
            }

            File tempFile = new File(TEMP_DIR + fileHash + ".json");
            file.transferTo(tempFile);
            networkService.loadTopology(tempFile.getAbsolutePath());
            return Response.success("Topology loaded successfully and saved to temp folder!");
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    /**
     * 默认加载 resources/topology.json 文件
     */
    @ApiOperation(value = "默认加载拓扑")
    @PostMapping("/defaultLoad")
    public Response<String> defaultLoadTopology() {
        try {
            networkService.loadTopology(DEFAULT_TOPOLOGY_FILE);
            return Response.success("Default topology loaded successfully!");
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    /**
     * 清理网络
     */
    @ApiOperation(value = "清理网络")
    @DeleteMapping("/clear")
    public Response<String> clearNetwork() {
        try {
            networkService.clearNetwork();
            return Response.success("Network cleared successfully!");
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    @GetMapping("/attackerCount")
    public Response<Integer> getAttackerCount() {
        try {
            int count = networkService.getAttackerCount();
            return Response.success("Attacker count retrieved successfully!", count);
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    @GetMapping("/serverCount")
    public Response<Integer> getServerCount() {
        try {
            int count = networkService.getServerCount();
            return Response.success("Server count retrieved successfully!", count);
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    /**
     * 执行攻击
     */
    //todo 前端没写好有问题到时候要改
    @ApiOperation(value = "执行攻击")
    @PostMapping("/attack")
    public Response<String> attack(@RequestBody AttackRecordVo attackRecordvo) {
        try {
            networkService.executeAttack(attackRecordvo);
            return Response.success("Attack executed successfully!");
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    /**
     * 实时获取服务器流量信息
     */
    @ApiOperation(value = "实时获取服务器流量信息")
    @PostMapping("/serverTraffic")
    public Response<ServerTrafficVo> getServerInfo(@RequestBody String serverName) {
        try {
            String trafficInfo = networkService.getServerTrafficInfo(serverName);
            long rxBytes = 0;
            long txBytes = 0;
            String[] parts = trafficInfo.split(", ");
            for (String part : parts) {
                if (part.startsWith("RX bytes:")) {
                    rxBytes = Long.parseLong(part.split(":")[1].trim());
                } else if (part.startsWith("TX bytes:")) {
                    txBytes = Long.parseLong(part.split(":")[1].trim());
                }
            }
            ServerTrafficVo serverTrafficVo = new ServerTrafficVo(serverName, rxBytes, txBytes);
            return Response.success("Server traffic retrieved successfully!", serverTrafficVo);
        } catch (Exception e) {
            return Response.error("Error: " + e.getMessage());
        }
    }

    /**
     * 计算文件的哈希值（SHA-256）
     */
    private String calculateFileHash(MultipartFile file) throws IOException {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] fileBytes = file.getBytes();
            byte[] hashBytes = digest.digest(fileBytes);
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            throw new IOException("Failed to calculate file hash", e);
        }
    }
}
